package com.example.myapplication.Service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.example.myapplication.Helper.ImportantdayHelper;
import com.example.myapplication.ImportantdayActivity;
import com.example.myapplication.R;
import com.example.myapplication.bean.ImportBean;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Calendar;

public class ImportantdayService extends Service {
    private NotificationManager manager;
    private Notification notification;
    private ArrayList<ImportBean> importBeans = new ArrayList<ImportBean>();
    private ImportantdayHelper importantdayHelper;
    private SQLiteDatabase database;

    public ImportantdayService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();

        //创建数据库
        importantdayHelper = new ImportantdayHelper(this, "importantday.db", null, 1);
        database = importantdayHelper.getReadableDatabase();

        notification();
        //多线程查询数据库内容
        new Thread() {
            @Override
            public void run() {
                super.run();
                //获取当前时间
                while (true) {
                    //查询数据库
                    initdataSet();
                    //获取系统时间
                    Calendar calendar = Calendar.getInstance();
                    String year = String.valueOf(calendar.get(Calendar.YEAR));
                    String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
                    String day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
                    String hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
                    String min = String.valueOf(calendar.get(Calendar.MINUTE));
                    for (int i = 0; i < importBeans.size(); i++) {
                        if (year.equals(importBeans.get(i).getYear()) && month.equals(importBeans.get(i).getMonth()) && day.equals(importBeans.get(i).getDay()) & hour.equals(importBeans.get(i).getHour())&&min.equals(importBeans.get(i).getMin())) {
                                //发送通知
                                manager.notify(1, notification);
                        }
                    }
                    try {
                        //休眠20s继续提醒
                        Thread.sleep(20000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 查询列表数据(数据库中)
     **/
    public void initdataSet() {
        String sql = "select * from importantday";
        Cursor cursor = database.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            Log.v("title", cursor.getString(1));
            Log.v("date", cursor.getString(2) + "年" + cursor.getString(3) + "月" + cursor.getString(4) + "日");
            Log.v("time", cursor.getString(5) + "时" + cursor.getString(6) + "分");
            ImportBean importBean = new ImportBean(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6));
            importBeans.add(importBean);
        }
        Log.v("result", cursor.toString());
    }

    //通知管理器
    private void notification() {
        //获取系统的通知管理器
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //2.安卓8.0以上版本的通知需要创建NotificationChannel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("june", "通知", NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
        }
        //4.设置跳转意图
        Intent intent = new Intent(this, ImportantdayActivity.class);
        @SuppressLint("UnspecifiedImmutableFlag") PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        //3.使用Builder构造器创建Notification对象，通知设置
        notification = new NotificationCompat.Builder(this, "june")
                .setDefaults(Notification.DEFAULT_ALL)
                .setTicker("您有一个提醒~")
                .setContentTitle("重要日提醒")
                .setContentText("今天有重要提醒，不要忘了喔~")
                .setSmallIcon(R.drawable.message_small)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.message_large))
                .setColor(Color.parseColor("#ff0000"))
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .build();

    }
}